package com.hk.core.security.cas;

import lombok.RequiredArgsConstructor;
import org.apereo.cas.client.proxy.ProxyGrantingTicketStorageImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.SecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * CAS 认证地址
 */
@RequiredArgsConstructor
public class CasAuthenticationSecurityConfigurer implements SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> {

    private final String processUrl;

    private final ServiceProperties serviceProperties;

    @Override
    public void init(HttpSecurity builder) {
        // ignore.
    }

    @Override
    public void configure(HttpSecurity builder) {
        var casAuthenticationFilter = new CasAuthenticationFilter();
        casAuthenticationFilter.setServiceProperties(serviceProperties);
        casAuthenticationFilter.setFilterProcessesUrl(processUrl);
        casAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        casAuthenticationFilter.setProxyGrantingTicketStorage(new ProxyGrantingTicketStorageImpl());
        builder.addFilterBefore(casAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
